package com.gulimall.order.conf;

import com.guli.common.vo.MemberTo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author WZH
 * @title: OrderInterceptor
 * @projectName gulimall-java
 * @description:
 * @date 2022/2/9
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberTo> memberLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行路径
        String URI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/order/order/status/**", URI);
        boolean match2 = antPathMatcher.match("/payed/notify", URI);
        if (match||match2){
            return true;
        }

        //获取登录信息(session共享)
        MemberTo member = (MemberTo) request.getSession().getAttribute("member");
        if (member!=null){
            //把登录后用户的信息放在ThreadLocal里面进行保存
            memberLocal.set(member);
            return true;
        }else {
            //未登录，返回登录页面
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<script>alert('请先进行登录，再进行后续操作！');location.href='http://auth.gulimall.com'</script>");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
